package com.is2.patchinglife.manager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.content.Context;
import android.util.Log;

/** Utility to read & write trophy & config file from disk **/

public class FileManager {

	private Context context;		//Needed to allow I/O operation
	

	/** Constructor **/
	public FileManager(Context _context){
		context = _context;
	}
	
	/** Return Application Context**/
	public Context getContext(){
		return context;
	}

	/** Read a file content and return it as a String
	 *  if file is not found, /assets/ is checked for the template file, else exception is thrown
	**/
	public String read(String _filename){
		
		String content = "";
		
		// if exists, try to read the local file
		try{
			//get the stream & append the content to a var
			BufferedReader reader = new BufferedReader(new InputStreamReader(context.openFileInput(_filename)));
			String temp = "";
			while((temp = reader.readLine()) != null)
				content += temp;
			reader.close();
		
		// if no local file exists, read the template in /assets/ and clone it to a local copy
		}catch(FileNotFoundException e){
			
			content = readFromAssets(_filename);
			
			// check if the file read are the initial one
			if(_filename=="got_trophy.json" || _filename=="conf.json")
				write(content,_filename);
			
		}catch(IOException e){
			Log.e("FileManager"," IOException while trying to read "+_filename);
			e.printStackTrace();
		}
		
		return content;
	}
	
	/** Try to read the template file "_filename" **/
	public String readFromAssets(String _filename){
		
		String content = "";
		try {
				// get the stream & append the content to a var
				BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().getAssets().open(_filename)));
				String temp = "";
				while((temp = reader.readLine()) != null)
					content += temp;
				reader.close();
			
			}catch(IOException e1){
				Log.e("FileManager"," IOException while trying to read "+_filename+" from /assets/");	
				e1.printStackTrace();
			}
		
		return content;
	}
	
	/** try top open _filename a write _input in it **/
	public void write(String _input, String _filename){
		try {
			// get the stream & write
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(context.openFileOutput(_filename,Context.MODE_PRIVATE)));
			writer.write(_input);
			writer.flush();
			writer.close();
		}catch(IOException e){
			Log.e("FileManager"," IOException while trying to read "+_filename);
			e.printStackTrace();
		}
		
	}
	
}